package com.boarsoft.log.core;

import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.boarsoft.log.entity.DesensitiveRule;
import com.boarsoft.log.util.DesensitiveUtil;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

/**
 * @Description: 重写MessageConverter的convert方法，加入脱敏逻辑 配置说明：
 *               需要在logback-spring.xml中加入conversionRule配置，如果有原有配置需要更改
 *               “<conversionRule conversionWord="msg" converterClass=
 *               "com.example.springlog.converter.DesensitiveMessageConverter"/>”
 * @Author: 刘超
 * @Date: 2023-06-01 10:45
 */
public class DesensitiveMessageConverter extends MessageConverter {

	public static final String DESENSITIVE_KEY = "desensitive";

	public static final String DESENSITIVE_TRUE = "true";

	public static final String DESENSITIVE_FALSE = "false";

	public static final String DESENSITIVE_RULE = "desensitiveRule";

	@SuppressWarnings("unchecked")
	@Override
	public String convert(ILoggingEvent event) {
		String formattedMessage = event.getFormattedMessage();
		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
		String sensitive = lc.getProperty(DESENSITIVE_KEY);
		List<DesensitiveRule> rules = (List<DesensitiveRule>) lc.getObject(DESENSITIVE_RULE);
		if (StringUtils.hasLength(sensitive) && DESENSITIVE_TRUE.equals(sensitive) && !CollectionUtils.isEmpty(rules)) {
			formattedMessage = DesensitiveUtil.desensitive(formattedMessage, rules);
		}
		return formattedMessage;
	}
}
